package com.chuji.crmcj.act;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.LoanForHistoryDetailsInfo;
import com.chuji.crmcj.bean.LoanForHistoryInfo;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.util.ArrayList;
import java.util.List;

public class LendHistoryActivity extends Activity {
    /*回退*/
    private ImageView mIv_Back;
    /*历史记录*/
    private ExpandableListView mLv_lend_history;
    //历史记录数据存储
    List<LoanForHistoryInfo.ApiParamObjEntity> loanForHistoryData;
    //历史记录网络数据
    LoanForHistoryInfo LoanForHistoryInfo;
    //历史记录详情数据存储
    List<LoanForHistoryDetailsInfo.ApiParamObjEntity> loanForHistoryDetailsData;
    //历史记录详情网络数据
    LoanForHistoryDetailsInfo loanForHistoryDetailsInfo;
    /*自定义适配器*/
    private CustomClientLendInfoAdapter customClientLendInfoAdapter;
    //销售员ID
    String SalerId;
    //客户ID
    String CustomerID;
    //意图
    Intent intent;
    private ArrayList<String> mData=new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lend_history);
        //初始化组件
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        mLv_lend_history = (ExpandableListView) findViewById(R.id.lv_lend_history);
        //设置点击事件
        mIv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //获取ID
        intent=getIntent();
        CustomerID=intent.getStringExtra("CustomerID");
        //获得数据
        reqDataBySale();
        reqDataDetailsBySale();
        mLv_lend_history.setGroupIndicator(null);
//        //给ListView设置点击事件
//        mLv_lend_history.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
////                UIUtils.startActivity(new Intent(UIUtils.getContext(), ClientDetailAct.class));
//                return true;
//            }
//        });
    }
    /**
     * 请求贷款记录历史记录
     */
    private void reqDataBySale() {
        if(loanForHistoryData==null){
            loanForHistoryData=new ArrayList<LoanForHistoryInfo.ApiParamObjEntity>();
        }
        SalerId= SPUtils.getString(UIUtils.getContext(), "UserID", "");
//        String strURL = String.format(UrlUtils.GETHIDDENLISt + "&SalesID=F248611C-CB39-4806-919E-71DCD085D208&CarModel=&CustomerLevel=&SeqType=0&PageSize=10&PageIndex=1");
        String strURL = String.format(UrlUtils.GET_LOAN_HISTORY + "&SalesID="+SalerId+"&PageSize=10&PageIndex=1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                LoanForHistoryInfo = JSON.parseObject(response, LoanForHistoryInfo.class);
                loanForHistoryData.addAll(LoanForHistoryInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customClientLendInfoAdapter == null) {
                            //创建适配器
                            customClientLendInfoAdapter=new CustomClientLendInfoAdapter();
                            //填充数据
                            mLv_lend_history.setAdapter(customClientLendInfoAdapter);
                        } else {
                            customClientLendInfoAdapter.notifyDataSetChanged();
                        }
                        //遍历所有group,将所有项设置成默认展开
                        int groupCount = mLv_lend_history.getCount();
                        for (int i=0; i<groupCount; i++)
                        {
                            mLv_lend_history.expandGroup(i);
                        };
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     *请求贷款记录历史记录详情
     */
    private void reqDataDetailsBySale() {
        if(loanForHistoryDetailsData==null){
            loanForHistoryDetailsData=new ArrayList<LoanForHistoryDetailsInfo.ApiParamObjEntity>();
        }
//        String strURL = String.format(UrlUtils.GETHIDDENLISt + "&SalesID=F248611C-CB39-4806-919E-71DCD085D208&CarModel=&CustomerLevel=&SeqType=0&PageSize=10&PageIndex=1");
        String strURL = String.format(UrlUtils.GET_LOAN_HISTORY_DETAILS+"&CustomerID="+CustomerID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loanForHistoryDetailsInfo=JSON.parseObject(response,LoanForHistoryDetailsInfo.class);
                loanForHistoryDetailsData.addAll(loanForHistoryDetailsInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     * 客户跟进适配器
     */
    class CustomClientLendInfoAdapter extends BaseExpandableListAdapter {
        ImageView iv_arr;
        TextView mTv_loan_date;
        TextView mTv_loan_money;
        TextView mTv_loan_lixi;
        TextView mTv_loan_year_limt;
        TextView mTv_totle_cost;
        TextView mTv_repay_month;
        TextView mTv_additional_cost;

        @Override
        public int getGroupCount() {
            return loanForHistoryData.size();
        }

        @Override
        public int getChildrenCount(int i) {
//            return loanForHistoryDetailsData.size();
            return loanForHistoryDetailsData.size();
        }

        @Override
        public Object getGroup(int i) {
            return loanForHistoryData.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return loanForHistoryDetailsData.get(i);
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int i, final boolean isExpanded, View convertView, ViewGroup viewGroup) {
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_lend_history_group, null);
                //初始化组件
                viewHolder.mTv_client_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.mTv_client_phoneNumber = (TextView) convertView.findViewById(R.id.tv_number);
                viewHolder.mTv_use_number = (TextView) convertView.findViewById(R.id.tv_num);
                iv_arr= (ImageView) convertView.findViewById(R.id.iv_arr);
                viewHolder.ll_next1 = (LinearLayout) convertView.findViewById(R.id.ll_next1);
                viewHolder.ll_next2 = (LinearLayout) convertView.findViewById(R.id.ll_next2);
                viewHolder.ll_check_detail = (LinearLayout) convertView.findViewById(R.id.ll_check_detail);
                if (!isExpanded) {
                    iv_arr.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
                } else {
                    iv_arr.setImageDrawable(UIUtils.getDrawable(R.drawable.iconup));
                }
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if(loanForHistoryData.size()!=0) {
                viewHolder.mTv_client_name.setText(loanForHistoryData.get(0).getName());
                if(loanForHistoryData.get(0).getTel().length()==11){
                    viewHolder.mTv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(loanForHistoryData.get(0).getTel()));
                }else{
                    viewHolder.mTv_client_phoneNumber.setText(loanForHistoryData.get(0).getTel());
                }
                viewHolder.mTv_use_number.setText(loanForHistoryData.get(0).getTotalCount());
            }else{
                UIUtils.showToastSafe("暂无历史记录");
            }
            //跳转到详情界面
            viewHolder.ll_next1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent=new Intent(UIUtils.getContext(), ClientDetailAct.class);
                    intent.putExtra("CustomerID",loanForHistoryData.get(0).getCustomerID());
                    startActivity(intent);
                }
            });
            viewHolder.ll_next2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent=new Intent(UIUtils.getContext(), ClientDetailAct.class);
                    intent.putExtra("CustomerID",loanForHistoryData.get(0).getCustomerID());
                    startActivity(intent);
                }
            });
            return convertView;
        }
        class ViewHolder{
            private TextView mTv_client_name;
            private TextView mTv_client_phoneNumber;
            private TextView mTv_use_number;
            private LinearLayout ll_next1;
            private LinearLayout ll_next2;
            private LinearLayout  ll_check_detail;
        }
        @Override
        public void onGroupExpanded(int groupPosition) {
            super.onGroupExpanded(groupPosition);
            int totalGroup = getGroupCount();
            for (int i = 0; i < totalGroup; i++) {
                if (i != groupPosition) {
                    mLv_lend_history.collapseGroup(i);
                    iv_arr.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
                    this.notifyDataSetChanged();
                }
            }
        }
        @Override
        public View getChildView(int i, int i1, boolean b, View convertView, ViewGroup viewGroup) {

            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_lend_history_child, null);
                reqDataDetailsBySale();
                //初始化组件
                mTv_loan_date = (TextView) findViewById(R.id.tv_loan_date);
                mTv_loan_money = (TextView) findViewById(R.id.tv_loan_money);
                mTv_loan_lixi = (TextView) findViewById(R.id.tv_loan_lixi);
                mTv_loan_year_limt = (TextView) findViewById(R.id.tv_loan_year_limt);
                mTv_totle_cost = (TextView) findViewById(R.id.tv_totle_cost);
                mTv_repay_month = (TextView) findViewById(R.id.tv_repay_month);
                mTv_additional_cost = (TextView) findViewById(R.id.tv_additional_cost);
            } else {

            }
            if(loanForHistoryDetailsData.size()!=0) {
                mTv_loan_date.setText(loanForHistoryDetailsData.get(0).getCreateTime());
                mTv_loan_money.setText(loanForHistoryDetailsData.get(0).getAmount());
                mTv_loan_lixi.setText(loanForHistoryDetailsData.get(0).getRate());
                mTv_loan_year_limt.setText(loanForHistoryDetailsData.get(0).getYears());
                mTv_totle_cost.setText(loanForHistoryDetailsData.get(0).getTotalAmount());
                mTv_repay_month.setText(loanForHistoryDetailsData.get(0).getMonthAmount());
                mTv_additional_cost.setText(loanForHistoryDetailsData.get(0).getMonthAmount());
            }else {
                UIUtils.showToastSafe("暂无详细历史记录");
            }
            return convertView;
        }
        //    class ViewHolder2 {
//        private TextView mTv_loan_date;
//        private TextView mTv_loan_money;
//        private TextView mTv_loan_lixi;
//        private TextView mTv_loan_year_limt;
//        private TextView mTv_totle_cost;
//        private TextView mTv_repay_month;
//        private TextView mTv_additional_cost;
//    }
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }
}
